package com.kehao.accountbook;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kehao.accountbook.network.Network;
import com.kehao.accountbook.network.TwoCaseCallBack;
import com.kehao.accountbook.pojo.User;

public class LoginActivity extends AppCompatActivity {

    private static final int REQUEST_REGISTER_CODE=1;
    private static final int UPDATA_VIEW=1;

    private EditText et_username;
    private EditText et_password;
    private String username = null;
    private String password = null;
    private ProgressBar progressBar;
    private Button btnLogin;
    private CheckBox cb_rempwd;

    private Handler handler;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    private void init(){
        sharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        progressBar = findViewById(R.id.pb_bar);
        progressBar.setVisibility(View.INVISIBLE);
        btnLogin = findViewById(R.id.btn_login);
        cb_rempwd = findViewById(R.id.cb_rempwd);
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case UPDATA_VIEW:
                        String text = msg.getData().getString("fail");
                        Toast.makeText(LoginActivity.this, text, Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.INVISIBLE);
                        break;
                }
            }
        };
        boolean rempwd ;
        rempwd = sharedPreferences.getBoolean("rempwd",false);
        username = sharedPreferences.getString("username","");
        password = sharedPreferences.getString("password","");
        if((!username.equals(""))&&(!password.equals(""))){
            if(rempwd){
                et_username.setText(username);
                et_password.setText(password);
                cb_rempwd.setChecked(rempwd);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_REGISTER_CODE:
                if (resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    username = bundle.getString("username");
                    password = bundle.getString("password");
                    et_username.setText(username);
                    et_password.setText(password);
                }
                break;

        }
    }

    public void onClickRegister(View view) {
        Intent intent=new Intent(this,RegisterActivity.class);
        startActivityForResult(intent,REQUEST_REGISTER_CODE);
    }

    public void onClickLogin(View view) {
        //关闭键盘
        closeKeyboard();

        username = et_username.getText().toString();
        password = et_password.getText().toString();
        if(username.equals("")||password.equals("")){
            Toast.makeText(LoginActivity.this, "请在文本框内填写用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }else {
            User user = new User(username,password);
            String json =new Gson().toJson(user);
            Network network = new Network(new TwoCaseCallBack() {
                @Override
                public void success(String string) {
                    if(string.equals("ok")){
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        getAccountApplication().setLoginstatus(true);
                        getAccountApplication().setUsername(username);
                        getAccountApplication().setPassword(password);
                        getAccountApplication().setRempwd(cb_rempwd.isChecked());
                        editor = sharedPreferences.edit();
                        editor.putBoolean("rempwd",cb_rempwd.isChecked());
                        editor.putString("username",username);
                        editor.putString("password",password);
                        editor.apply();
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }else if (string.equals("fail")){
                        Message message = new Message();
                        message.what = UPDATA_VIEW;
                        Bundle bundle = new Bundle();
                        bundle.putString("fail","用户名或密码错误");
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
                @Override
                public void fail() {
                    Message message = new Message();
                    message.what = UPDATA_VIEW;
                    Bundle bundle = new Bundle();
                    bundle.putString("fail","网络异常");
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            },json,Network.LOGIN_URL,getAccountApplication());
            network.send();
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    private void closeKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    private AccountApplication getAccountApplication(){
        return (AccountApplication)getApplication();
    }
}
